package com.medi.chats.controller.page.m;

import com.medi.chats.config.WxMpConfig;
import com.medi.chats.model.McUsers;
import com.medi.chats.service.user.UserService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述:
 * 微信公众号回调类
 *
 * @outhor Administrator
 * @create 2018-11-09 9:46
 */
@Controller
@RequestMapping("/wx/cb")
public class WxMpCbController {

    @Autowired
    UserService userService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @GetMapping("/userInfoMp")
    public String userInfo(@RequestParam("code") String code,
                           HttpServletRequest request){
        WxMpService mpService = WxMpConfig.getMpService();

        HttpSession session = request.getSession();
        try {
            WxMpOAuth2AccessToken accessToken = mpService.oauth2getAccessToken(code);
            WxMpUser user = mpService.oauth2getUserInfo(accessToken, null);

            // 数据库查询用户
            Map<String, Object> map = new HashMap<>();
            map.put("openId", user.getOpenId());
            McUsers mcUsers = userService.getUserInfoByOpenId(map);
            // 没有获取到用户信息，则插入当前用户
            if (mcUsers == null) {
                mcUsers.setOpenid(user.getOpenId());
                mcUsers.setAvatarUrl(user.getHeadImgUrl());
                mcUsers.setNickName(user.getNickname());
                mcUsers.setUnionid(user.getUnionId());
                mcUsers.setGender(user.getSex());
                mcUsers.setUserType(1);
                mcUsers.setCreatedAt(new Date());
                mcUsers.setUpdatedAt(new Date());
                long userId = userService.insertUserBackWithId(mcUsers);
                if (userId > 0) {
                    mcUsers.setId(userId);
                    session.setAttribute("chatUser", mcUsers);
                }
            } else {
                // 保存到session中
                session.setAttribute("chatUser", mcUsers);
            }

            // 跳转到请求的url
            return "redirect:" + session.getAttribute("targetUrl");
        } catch (WxErrorException e) {
            e.printStackTrace();
            // 请求失败，跳转到home页面  TODO
            return "redirect:" + session.getAttribute("targetUrl");
        }
    }
}
